package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.xml.transform.Result;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {

        try{
            int page = params.getPage(),size = params.getSize();
            // 1.准备request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            buildBasicQuery(params,request);

            // 2.2 排序
            // 如果开启了竞价排名，则不能使用排序
            // request.source().sort("price", SortOrder.ASC);
            String location = params.getLocation();
            if(location != null && !"".equals(location)){
                request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }
            // 2.3添加分页
            request.source().from((page-1)*size).size(size);
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters() {
        try{
            // 1. 准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2. 准备DSL
            // 2.1. 设置size
            request.source().size(0);
            // 2.2. 聚合
            buildAggregation(request);
            // 3. 发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4. 解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1 根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            result.put("品牌",brandList);
            // 4.2 根据城市名称，获取品牌结果
            List<String> cityList = getAggByName(aggregations,"cityAgg");
            result.put("城市",cityList);
            // 4.3 根据星级名称，获取品牌结果
            List<String> starList = getAggByName(aggregations,"starAgg");
            result.put("星级",starList);
            return result;
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try{
            // 1. 准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2. 准备DSL
            // 2.1. query
            buildBasicQuery(params,request);
            // 2.2. 设置size
            request.source().size(0);
            // 2.3. 聚合
            buildAggregation(request);
            // 3. 发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4. 解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1 根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            result.put("品牌",brandList);
            // 4.2 根据城市名称，获取品牌结果
            List<String> cityList = getAggByName(aggregations,"cityAgg");
            result.put("城市",cityList);
            // 4.3 根据星级名称，获取品牌结果
            List<String> starList = getAggByName(aggregations,"starAgg");
            result.put("星级",starList);
            return result;
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1. 根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2. 获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3. 遍历
        List<String> brandList = new ArrayList<>();
        for(Terms.Bucket bucket: buckets){
            // 4.4. 获取可以
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );
    }

    private void buildBasicQuery(RequestParams params,SearchRequest request) {
        // 2.1 构建boolQuery
        String keywords = params.getKey();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 关键字搜索
        if(keywords == null || "".equals(keywords)){
            queryBuilder.must(QueryBuilders.matchAllQuery());
        }else{
            queryBuilder.must(QueryBuilders.matchQuery("all", keywords));
        }
        // 城市查询
        if(params.getCity() != null && !params.getCity().equals("")){
            queryBuilder.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        // 品牌查询
        if(params.getBrand() != null && !params.getBrand().equals("")){
            queryBuilder.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        // 星级条件
        if(params.getStarName() != null && !params.getStarName().equals("")){
            queryBuilder.filter(QueryBuilders.termQuery("starName",params.getStarName()));
        }
        // 价格
        if(params.getMaxPrice() != null && params.getMinPrice() != null){
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte( params.getMaxPrice()));
        }

        // 2. 算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        queryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD",true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        // request.source().query(queryBuilder);
        request.source().query(functionScoreQueryBuilder);
    }

    public PageResult search1(RequestParams params) {

        try{
            int page = params.getPage(),size = params.getSize();
            // 1.准备request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            // 2.1 关键字搜索
            String keywords = params.getKey();
            QueryBuilder queryBuilder;
            if(keywords == null || "".equals(keywords)){
                queryBuilder = QueryBuilders.matchAllQuery();
            }else{
                queryBuilder = QueryBuilders.matchQuery("all", keywords);
            }

            // 2.2 排序
            request.source().sort("price", SortOrder.ASC);
            // 2.3添加分页
            request.source().from((page-1)*size).size(size);
            request.source().query(queryBuilder);
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    private PageResult handleResponse(SearchResponse response) {
        // 4.解析响应结果
        SearchHits searchHits = response.getHits();//第一层命中数据hits
        // 4.1.获取总条数
        Long total = searchHits.getTotalHits().value;//获取总数
        System.out.println("共搜索到" + total + "条数据");
        // 4.2. 文档数组
        SearchHit[] hits = searchHits.getHits();//获取里层数据hits
        // 4.3. 遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            // 反序列号
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!CollectionUtils.isEmpty(highlightFields)){
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField != null){
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    hotelDoc.setName(name);
                }
            }
            // 获取到排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
            System.out.println("hotelDoc=" + hotelDoc);

        }
        // 4.4. 封装返回
        return new PageResult(total, hotels);
    }
}
